/*
 * @Author: dagu 243065157@qq.com
 * @Date: 2025-02-13 10:11:22
 * @LastEditors: dagu 243065157@qq.com
 * @LastEditTime: 2025-03-07 14:24:36
 * @FilePath: \format-bug-msg\src\contexts\HistoryContext.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { createContext, useContext, useState, useEffect } from 'react';
import { HistoryItem, HistoryContextType } from '../types/history';

const HistoryContext = createContext<HistoryContextType | null>(null);

export const useHistory = () => {
  const context = useContext(HistoryContext);
  if (!context) {
    throw new Error('useHistory must be used within a HistoryProvider');
  }
  return context;
};

export const HistoryProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [history, setHistory] = useState<HistoryItem[]>(() => {
    const saved = localStorage.getItem('bugHistory');
    return saved ? JSON.parse(saved) : [];
  });

  useEffect(() => {
    localStorage.setItem('bugHistory', JSON.stringify(history));
  }, [history]);

  const addHistory = (data: Omit<HistoryItem['data'], 'id'>) => {
    const newItem: HistoryItem = {
      id: Date.now().toString(),
      timestamp: Date.now(),
      data: data as HistoryItem['data']
    };
    setHistory(prev => [newItem, ...prev].slice(0, 50)); // 只保留最近50条记录
  };

  const deleteHistory = (id: string) => {
    setHistory(prev => prev.filter(item => item.id !== id));
  };

  const clearHistory = () => {
    setHistory([]);
  };

  const value = {
    history,
    addHistory,
    deleteHistory,
    clearHistory
  };

  return <HistoryContext.Provider value={value}>{children}</HistoryContext.Provider>;
};
